import {useSelector, useDispatch} from "react-redux";
import {Link} from "react-router-dom";
import {useState} from "react";
import CommentList from "@/pages/comment/components/commentList.jsx"
import {createCommentAction} from "@/store/actions/commentAction.js";

export default function Comment({slug}) {
    const dispatch = useDispatch();
    const currentUser = useSelector(state => state.user)
    const [body, setBody] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault()
        dispatch(createCommentAction(slug, body))
        setBody("")
    }
    return (
        <div className="col-xs-12 col-md-8 offset-md-2">
            {
                !currentUser ? (
                    <p>
                        <Link to="/login"> 登录</Link>
                        &nbsp; or &nbsp;
                        <Link to="/regist"> 注册</Link>
                    </p>
                ) : (
                    <form className="card comment-form" onSubmit={handleSubmit}>
                        {/*  登录 : 评论form 提交按钮  */}
                        <div className="card-block">
                            <textarea
                                className="form-control"
                                placeholder='添加评论'
                                rows="3"
                                style={{resize: "none"}}
                                value={body}
                                onChange={(e) => {
                                    setBody(e.target.value)
                                }}
                            />
                        </div>
                        <div className="card-footer">
                            <img
                                className="comment-author-img"
                                src={currentUser && (currentUser.avatar || "https://img1.baidu.com/it/u=3425716258,3217626939&fm=253&fmt=auto&app=138&f=PNG?w=182&h=182")}
                                alt="avatar"/>
                            <button
                                className="btn btn-sm btn-primary"
                                type="submit"
                            >
                                提交
                            </button>
                        </div>

                    </form>
                )
            }
            {/*    评论列表*/}
            <CommentList slug={slug}/>
        </div>
    )
}